<template>
  <van-pull-refresh v-model="pullRefreshLoading" @refresh="onPullRefresh">
    <div class="header-container">
      <nav-bar :title="categoryName" :showLeftArrow="true" :leftText="'返回'" @click-left="back" />
    </div>
    <div class="main-container">
      <div class="van-list-container">
        <van-list v-model:loading="listLoading" :finished="listFinished" :immediate-check="false" :offset="50"
          finished-text="没有更多了" @load="onListLoad">
          <div class="product-container">
            <template v-if="products && products.length > 0">
              <div class="product-list">
                <template v-for="item of products" :key="item.id">
                  <div class="product-item" @click="showProductDetail(item)">
                    <img :src="item.imgUrl" alt="" />
                    <div class="product-info">
                      <div class="product-title">
                        <van-tag round type="danger">自营</van-tag>
                        {{ item.name }}
                      </div>
                      <div class="product-footer">
                        <div class="product-price">¥ {{ item.price }}</div>
                        <div class="product-action">
                          <van-icon name="shopping-cart-o" @click="addCartItem(item, $event)" />
                        </div>
                      </div>
                    </div>
                  </div>
                </template>
              </div>
            </template>
            <van-empty v-else />
          </div>
        </van-list>
      </div>
    </div>
  </van-pull-refresh>
</template>
<script lang="ts">
import { defineComponent, onMounted, reactive, toRefs } from "vue";
import TabBar from "@/components/TabBar.vue";
import productService from "@/services/product.service";
import PmsProduct from "@/entity/PmsProduct";
import { AxiosError } from "axios";
import { Toast } from "vant";
import { useRoute, useRouter } from "vue-router";
import Page from "@/entity/Page";
import OmsCartItemCreationParam from "@/entity/OmsCartItemCreationParam";
import cartItemService from "@/services/cart-item.service";
import NavBar from "@/components/NavBar.vue";
import ProductQueryParam from "@/entity/ProductQueryParam";

type StateType = {
  listLoading: boolean;
  listFinished: boolean;
  pullRefreshLoading: boolean;
  queryParam: ProductQueryParam;
  products: PmsProduct[];
  page?: Page<PmsProduct>;
  categoryId?: number;
  categoryName?: string;
  qtext?: string;
};

export default defineComponent({
  components: {
    NavBar,
    TabBar,
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const state = reactive<StateType>({
      listLoading: false,
      listFinished: false,
      pullRefreshLoading: false,
      queryParam: {},
      products: new Array<PmsProduct>(),
      page: undefined,
      categoryId: undefined,
      categoryName: undefined,
    });

    onMounted(() => {
      state.categoryId =
        route.query && route.query.categoryId != null
          ? Number(route.query.categoryId)
          : undefined;
      state.categoryName =
        route.query && route.query.categoryName != null
          ? String(route.query.categoryName)
          : undefined;
      state.queryParam.categoryId = state.categoryId;
      state.qtext = route.query && route.query.qtext != null
        ? String(route.query.qtext)
        : undefined;
        state.queryParam.qtext = state.qtext;
      load(state.queryParam);
    });

    const load = async (queryParam?: ProductQueryParam) => {
      try {
        state.listLoading = true;
        const page = await productService.query(queryParam);
        state.page = page;

        state.queryParam.page = page.number + 1;
        state.queryParam.size = page.size;

        state.products = [...state.products, ...page.content];
        state.listFinished = state.page.last;
      } catch (e) {
        if (e instanceof AxiosError && e.response?.status == 401) {
          Toast.fail("请先登录");
          router.push("/login");
          return;
        }
        Toast.fail("加载失败");
        throw e;
      } finally {
        state.listLoading = false;
      }
    };

    const back = () => {
      router.back();
    };

    const onListLoad = () => {
      load(state.queryParam);
    };

    const showProductDetail = (p: PmsProduct) => {
      router.push({
        path: "/product-detail",
        query: {
          id: p.id,
        },
      });
    };

    const addCartItem = async (p: PmsProduct, evt: MouseEvent) => {
      evt.stopPropagation();
      evt.stopImmediatePropagation();
      try {
        const param: OmsCartItemCreationParam = {
          productId: p.id,
          quantity: 1,
        };
        await cartItemService.createOrUpdate(param);
      } catch (e) {
        if (e instanceof AxiosError && e.response?.status == 401) {
          Toast.fail("请先登录");
          router.push("/login");
          return;
        }
        Toast.fail("加载失败");
        throw e;
      } finally {
      }
    };

    const onPullRefresh = async () => {
      try {
        state.pullRefreshLoading = true;
        await load(state.queryParam);
      } catch (e) {
        throw e;
      } finally {
        state.pullRefreshLoading = false;
      }
    };

    return {
      ...toRefs(state),
      onListLoad,
      back,
      showProductDetail,
      addCartItem,
      onPullRefresh,
    };
  },
});
</script>

<style scoped>
.header-container {
  position: fixed;
  top: 0;
  height: 46px;
  left: 0;
  width: 100%;
}

.main-container {
  position: fixed;
  top: 46px;
  bottom: 0;
  left: 0;
  width: 100%;
}

.van-list-container {
  height: 100%;
  overflow-y: scroll;
}

.product-container {}

.product-list {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
}

.product-item {
  box-sizing: border-box;
  width: 50%;
  border-bottom: 1px solid #e9e9e9;
  padding: 10px 10px;
}

.product-item img {
  display: block;
  width: 120px;
  height: 120px;
  margin: 0 auto;
}

.product-info {
  font-size: 14px;
  padding: 10px 0;
}

.product-title {
  color: #222333;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.product-footer {
  justify-content: space-between;
  display: flex;
  flex-direction: row;
}

.product-price {
  color: var(--van-danger-color);
}

.product-action {}

.product-item:nth-child(2n + 1) {
  border-right: 1px solid #e9e9e9;
}
</style>
